<template>
  <div class="pdf">
    <div class="frame">
      <div class="center">
        <div class="profile">
          <div class="name">PDF转图片</div>
          <div class="job">文档大小10Mb</div>
          <div class="actions">
            <a href="javascript:;" class="btn file">
              Choose Pdf
              <input id="pdf" type="file" accept="application/pdf" @change="pdfchange()" />
            </a>
            <button class="btn" id="export" @click="exportclick()">Export Image</button>
          </div>
        </div>

        <div class="stats">
          <div class="box">
            <span class="value">名称</span>
            <span class="parameter" id="pdfName"></span>
          </div>
          <div class="box">
            <span class="value">大小</span>
            <span class="parameter" id="sizeText"></span>
          </div>
          <div class="box">
            <span class="value">页数</span>
            <span class="parameter" id="pagesText"></span>
          </div>
        </div>
      </div>
    </div>

    <div id="imgDiv"></div>
  </div>
</template>
<script>

export default {
  name: "Pdfsdy",
  data() {
    return {
      // pdfFile
    };
  },
  methods: {
    pdfinit() {
      $("#export").attr("disabled", "disabled"); //禁用导出图片按钮
    },
    pdfchange() {
      var _self = this;
      var pdfFileURL = $("#pdf").val();
      if (pdfFileURL) {
        $("#imgDiv").empty(); //清空上一PDF文件展示图
        var files = $("#pdf").prop("files"); //获取到文件
        var fileSize = files[0].size;
        var mb;
        if (fileSize) {
          mb = fileSize / 1048576;
          if (mb > 10) {
            alert("文件大小不能>10M");
            return;
          }
        }

        $("#export").removeAttr("disabled", "disabled");
        $("#pdfName")
          .text(files[0].name)
          .attr("title", files[0].name);
        $("#sizeText").text(mb.toFixed(2) + "Mb");

        /*pdf.js无法直接打开本地文件,所以利用FileReader转换*/
        var reader = new FileReader();
        reader.readAsArrayBuffer(files[0]);
        reader.onload = function(e) {
          var myData = new Uint8Array(e.target.result);
          var docInitParams = {
            data: myData
          };
          var typedarray = new Uint8Array(this.result);
          PDFJS.getDocument(typedarray).then(function(pdf) {
            //PDF转换为canvas
            $("#imgDiv").css("border", "0"); //清除文本、边框
            if (pdf) {
              var pageNum = pdf.numPages;
              $("#pagesText").text(pageNum);

              for (var i = 1; i <= pageNum; i++) {
                var canvas = document.createElement("canvas");
                canvas.id = "pageNum" + i;
                $("#imgDiv").append(canvas);
                var context = canvas.getContext("2d");
                _self.openPage(pdf, i, context);
              }
            }
          });
        };
      }
    },
    openPage(pdfFile, pageNumber, context) {
      var scale = 2;
      pdfFile.getPage(pageNumber).then(function(page) {
        var viewport = page.getViewport(scale); // reference canvas via context
        var canvas = context.canvas;
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        canvas.style.width = "100%";
        canvas.style.height = "100%";
        var renderContext = {
          canvasContext: context,
          viewport: viewport
        };
        page.render(renderContext);
      });
      return;
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
    exportclick() {
      var _self = this;
      var zip = new JSZip();
      var images = zip.folder("images");
      $("canvas").each(function(index, ele) {
        var canvas = document.getElementById("pageNum" + (index + 1));
        images.file(
          "image-" + (index + 1) + ".png",
          _self.dataURLtoBlob(canvas.toDataURL("image/png", 1.0)),
          {
            base64: true
          }
        );
      });
      zip
        .generateAsync({
          type: "blob"
        })
        .then(function(content) {
          saveAs(content, "pdftoimages.zip");
        });
    }
  },
  mounted(){
       this.pdfinit()
  }
};
</script>

<style>
</style>